package com.message;

import android.util.Log;

import com.util.LogUtil;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.keepalive.KeepAliveFilter;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;
import org.apache.mina.filter.keepalive.KeepAliveRequestTimeoutHandler;

/**
 * Created by Mars on 2017/9/21.
 */

public class LotteryKeepAliveFilter extends KeepAliveFilter {


    private static final int INTERVAL = 10;
    private static final int TIMEOUT = 20;


    public LotteryKeepAliveFilter(KeepAliveMessageFactory messageFactory) {
        super(messageFactory, IdleStatus.BOTH_IDLE, new LotteryKeepAliveRequestTimeoutHandler(),
                INTERVAL, TIMEOUT);
    }

    public LotteryKeepAliveFilter() {
        super(new KeepAliveMessageFactoryImpl(), IdleStatus.READER_IDLE,
                new LotteryKeepAliveRequestTimeoutHandler(), INTERVAL, TIMEOUT);
        setForwardEvent(false); // 此消息不会继续传递，不会被业务层看见

    }

}

class LotteryKeepAliveRequestTimeoutHandler implements KeepAliveRequestTimeoutHandler {

    @Override
    public void keepAliveRequestTimedOut(KeepAliveFilter keepAliveFilter,
                                         IoSession ioSession) throws Exception {
        LogUtil.e("keepAliveRequestTimedOut");
        ioSession.close(true);
    }
}

/**
 * 当心跳机制启动的时候，需要该工厂类来判断和定制心跳信息
 */
class KeepAliveMessageFactoryImpl implements KeepAliveMessageFactory {

    @Override
    public boolean isRequest(IoSession ioSession, Object message) {
        return false;
    }

    @Override
    public boolean isResponse(IoSession ioSession, Object o) {
        MsgPacket mp = (MsgPacket) o;
        if (mp.mMsgType == MsgId.MSG_KEEP_LIVE)
            return true;
        else
            return false;
    }

    @Override
    public Object getRequest(IoSession ioSession) {
        return new MsgPacket(MsgId.MSG_KEEP_LIVE);
    }

    @Override
    public Object getResponse(IoSession ioSession, Object o) {
        return null;
    }
}